<template>
  <div id="con">
    <input type="file" @change="getImg" id="inputBtn">
    <span id="selectBtn">选择图片</span>
    <div id="imgBox" ref="imgBox"></div>
  </div>
</template>

<script>
  import myUtils from "../assets/myUtils";
  import Utils from "../assets/Util";
  import aliUtil from "../assets/aliUtil";
  export default {
    name: 'cutImg',
    data(){
      return {
        imgBox:null,
        img:null
      }
    },
    mounted(){
      this.imgBox = this.$refs.imgBox;
    },
    methods:{
      canvasDataURL(fileData, callback){
        let that = this;
        let reader = new FileReader();
        reader.onload = function (e) {
          let data = e.target.result;
          let image = new Image();
          image.src = data;
          image.setAttribute("crossOrigin", 'Anonymous');
          image.onload = function(){
            let w = image.width;
            let h = image.height;
            let scale = w / h;
            let imgBoxWidth = that.imgBox.clientWidth;
            if (w > imgBoxWidth && h > imgBoxWidth) {
              if (w > h) {
                h = imgBoxWidth;
                w = h * scale;
              } else {
                w = imgBoxWidth;
                h = w / scale;
              }
            } else if (w > imgBoxWidth || h > imgBoxWidth) {
              if (scale >= 0.5 && scale <= 2) {
                if (w > h) {
                  h = imgBoxWidth;
                  w = h * scale;
                } else {
                  w = imgBoxWidth;
                  h = w / scale;
                }
              }
            }else{
              if (w > h) {
                h = imgBoxWidth;
                w = h * scale;
              }else{
                w = imgBoxWidth;
                h = w / scale;
              }
            }
            // 生成canvas
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            // 创建属性节点
            let anw = document.createAttribute("width");
            anw.nodeValue = w;
            let anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(image, 0, 0, w, h);
            // 生成base64的图片数据
            let base64 = canvas.toDataURL('image/jpeg', 1);
            let fileSize = base64.length / 1024 / 1024;
            if (fileSize > 1) base64 = canvas.toDataURL('image/jpeg', 0.5);
            callback(base64);
          };
        };
        reader.readAsDataURL(fileData);
      },
      getImg(e){
        this.$refs.imgBox.innerHTML = "";
        let that = this;
        let bolbImg = e.target.files[0];
        let mime = bolbImg['type'].split("/")[0];
        if (mime !== "image") {
          alert("请选择图片");
        }
        this.canvasDataURL(bolbImg, function(value){
          that.img = new Image();
          that.img.src = value;
          that.img.style.cursor = "move";
          that.img.style.position = "absolute";
          that.img.setAttribute("ondragstart", "return false");
          that.img.addEventListener("mousemove", function(e){
            e.preventDefault && e.preventDefault();
          });
          that.img.onload = function(){
            that.imgBox.append(that.img);
          }
          let mouse = myUtils.init(that.imgBox);
          let mouseOnImgPos = {
            L:0,
            T:0
          };
          that.imgBox.addEventListener("mousedown", function(){
            if (mouse.isPressed) {
              mouseOnImgPos.L = mouse.x - that.img.offsetLeft;
              mouseOnImgPos.T = mouse.y - that.img.offsetTop;
            }
          });
          that.imgBox.addEventListener("mousemove", function(){
            if (mouse.isPressed) {
              that.img.style.left = mouse.x - mouseOnImgPos.L + "px";
              that.img.style.top = mouse.y - mouseOnImgPos.T + "px";
            }
          });
          that.imgBox.addEventListener("mouseup", function(){
            if(mouse.isPressed === false){
              let imgLeft = that.img.offsetLeft;
              let imgTop = that.img.offsetTop;
              let imgWidth = that.img.clientWidth;
              let imgHeight = that.img.clientHeight;
              let imgBoxWidth = this.clientWidth;
              let imgBoxHeight = this.clientHeight;
              if(imgLeft > 0){
                that.img.style.left = 0;
              }
              if (imgLeft < (imgBoxWidth - imgWidth)) {
                that.img.style.left = imgBoxWidth - imgWidth + "px";
              }
              if (imgTop > 0) {
                that.img.style.top = 0;
              }
              if (imgTop < (imgBoxHeight - imgHeight)) {
                that.img.style.top = imgBoxHeight - imgHeight + "px"
              }
            }
          });
        });
      },
      sureCut(callback){
        let that = this;
        let w = that.imgBox.clientWidth;
        let h = that.imgBox.clientHeight;
        let x = Math.abs(that.img.offsetLeft);
        let y = Math.abs(that.img.offsetTop);
        // 生成canvas
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        // 创建属性节点
        let anw = document.createAttribute("width");
        anw.nodeValue = w;
        let anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that.img, x, y, w, h, 0, 0, w, h);
        // 生成base64的图片数据
        let base64 = canvas.toDataURL('image/jpeg', 1);
        let resultBolbImg = Utils.dataURLtoBlob(base64);
        aliUtil.uploadThumbImg(resultBolbImg, function (result) {
            callback(result);
        });
      }
    }
  }
</script>

<style scoped>
  #con{
    position: relative;
  }
  #inputBtn{
    opacity: 0;
    position: absolute;
    left:20px;
    top:140px;
    width:100px;
    height:35px;
  }
  #selectBtn{
    float:left;
    margin-top:140px;
    margin-left:20px;
    width:100px;
    line-height:35px;
    text-align: center;
    color:#fff;
    background:#119C5B;
    border-radius: 4px;
    font-size:14px;
    cursor: pointer;
  }
  #imgBox{
    float:right;
    margin-right:20px;
    display: inline-block;
    width:300px;
    height:300px;
    border:1px dashed #C0C0C0;
    position: relative;
    overflow: hidden;
    border-radius: 150px;
    background:#F4F4F4;
  }
</style>
